package com.shw.pclient.adapter;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.BufferOverflowException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;

import com.shw.pclient.R;
import com.shw.pclient.ui.ShowWorkingActivity;
import com.shw.pclient.vo.WorkingInfo;

public class SHWNotifyAdapter {

	private static Notification notification;
	private static NotificationManager notificationManager;
	private static int NOTIFICATION_ID = 1;

	public static void addNotifiInfo(WorkingInfo workingInfo, Context context) {
		notification = new Notification();
		notification.icon = R.drawable.ic_launcher;
		notification.tickerText = context.getString(R.string.shw_work_alert);
		notification.when = System.currentTimeMillis();
		notification.defaults = Notification.DEFAULT_SOUND;
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Intent intent = new Intent(context, ShowWorkingActivity.class);
		intent.putExtra("body", workingInfo.getBody());
		intent.putExtra("dates", workingInfo.getDates());
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				intent, 0);
		notification.setLatestEventInfo(context,
				context.getString(R.string.shw_work_title),
				workingInfo.getBody(), pendingIntent);
		notificationManager.notify(NOTIFICATION_ID, notification);
		++NOTIFICATION_ID;
		writeInfoToFile(workingInfo);
	}

	public static void writeInfoToFile(WorkingInfo workingInfo) {
		File file = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/SHW/Working/working.dat");
		File files = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/SHW/Working");
		BufferedWriter bw=null;
		try {
			if (!files.exists()) {
				files.mkdirs();
			}
			bw=new BufferedWriter(new FileWriter(file,true));
			bw.append(workingInfo.getBody());
			bw.newLine();
			bw.append(workingInfo.getDates());
			bw.newLine();
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
